import { defineComponent } from 'vue';
import type { TableColumnsType } from 'ant-design-vue';
import SampleComponentBase from '/@/shared/component-base/sample-component-base';
import { SmileOutlined, DownOutlined } from '@ant-design/icons-vue';
import GDynamicTableToolbarBottom from '../components/toolbar/bottom-index.vue';
import { IListViewColumnsDto, ListViewColumnsActionItemDto } from '/@/shared/service-proxies';
export default defineComponent({
  props: {
    json: {
      type: Object,
      required: true,
      default: () => {},
    },
    columns: {
      type: Array,
      required: true,
      default: [] as Array<IListViewColumnsDto>,
    },
    // 必须要，自适应宽度，滚动条
    scroll: {
      type: Object,
      required: true,
    },
    tableProps: {
      type: Object,
      required: true,
    },
    dataSources: {
      type: Object,
      required: true,
    },
    pagination: {
      type: Object,
      required: true,
    },
    showExport: {
      type: Boolean,
      required: true,
    },
    showSelect: {
      type: Boolean,
      default: true,
      required: true,
    },
    /** 控制表格操作栏按钮隐藏 */
    showActionBtn: {
      type: Function,
      default: () => {
        return true;
      },
    },
  },
  data() {
    return {
      columnsList: [] as any,
    };
  },
  components: {
    SmileOutlined,
    DownOutlined,
    GDynamicTableToolbarBottom,
  },
  mixins: [SampleComponentBase],
  emits: ['tableChange', 'action-click'],
  watch: {
    formatColumns() {
      this.columnsList = this.formatColumns;
    },
  },
  computed: {
    /**
     * 计算返回的列格式
     */
    formatColumns(): TableColumnsType {
      return (this.columns as any)
        .map((item: IListViewColumnsDto) => {
          const { field, position, sortable } = item;
          return {
            ...item,
            title: this.l(item?.title ?? ''),
            dataIndex: field,
            key: field,
            align: position,
            ellipsis: true,
            sorter: sortable,
          };
        })
        .filter((item) => {
          return !!item.ifShow;
        })
        .sort((a, b) => {
          return a.sortNum - b.sortNum;
        });
    },

    /**
     * 计算type为link时的链接地址
     */
    linkPath() {
      return (column, record) => {
        let link = column.LinkPath;
        const params = column.LinkParam.split(',');
        params.forEach((item) => {
          link = link.replace('${' + item + '}', record[item]);
        });
        return link;
      };
    },
    hasGranted() {
      return (val) => {
        if (!val) return true;
        return this.isGranted(val);
      };
    },
    isMenuButtonEmpty() {
      return (item, column, record) => {
        const arr = item.filter((i) => {
          return this.hasGranted(i.acl) && this.formatShowActionBtn(i, column, record);
        });
        return arr.length > 0 ? false : true;
      };
    },
    /**
     * 背景颜色
     */
    bgColor() {
      return (column: IListViewColumnsDto, record) => {
        if (!column.listViewColumnColor) return '';
        let condition = false;
        if (record) {
        }
        if (column.type == 'datetime') {
          condition = eval(
            `this.formatDate(column, record) ${column.listViewColumnColor.determineType} column.listViewColumnColor.value`,
          );
        } else if (column.type == 'number') {
          condition = eval(
            `Number(this.formatNumber(column, record)) ${column.listViewColumnColor.determineType} Number(column.listViewColumnColor.value)`,
          );
        } else {
          condition = eval(
            `record[column.field] ${column.listViewColumnColor.determineType} column.listViewColumnColor.value`,
          );
        }
        const bg =
          column.field == column.listViewColumnColor.colFieldName && condition
            ? column.listViewColumnColor.color
            : '';
        const style = !!bg
          ? {
              background: bg,
              display: 'initial',
              color: 'white',
              padding: '6px 10px',
              'border-radius': '10px',
              'font-size': '12px',
            }
          : {};

        return style;
      };
    },
    /**
     * number
     */
    formatNumber() {
      return (column, record) => {
        const text = record[column.field];
        if (!text) return '';
        // 防止不是number报错
        if (typeof text != 'number') {
          const arr = text.toString().split('.');
          if (arr.length <= 1) {
            arr[1] = '00';
          }
          return `${arr[0]}.${arr[1].substr(0, column.numberDigits)}`;
        }
        return text.toFixed(column.numberDigits);
      };
    },
    currentNo() {
      return (index) => {
        if (!this.pagination) return index + 1;
        return (this.pagination.current - 1) * this.pagination.pageSize + (index + 1);
      };
    },
    formatDate() {
      return (column, record) => {
        const fieldValue = !!column.field ? record[column.field] : '';
        return this._moment(fieldValue, column.dateFormat);
      };
    },
    /** 控制表格操作栏按钮隐藏 */
    formatShowActionBtn() {
      return (
        item: ListViewColumnsActionItemDto,
        column: IListViewColumnsDto,
        record: any,
      ): boolean => {
        return this.showActionBtn(item, column, record);
      };
    },
  },
  methods: {
    /**
     * 表格分页、排序、筛选变化时触发
     */
    handleChangeClick(pagination, filters, sorter, { currentDataSource }) {
      this.$emit('tableChange', {
        pagination,
        filters,
        sorter,
        currentDataSource,
      });
    },
    handleMenuClick({ key }, record) {
      console.log(key, record);

      this.$emit('action-click', key, record);
    },
    handleActionClick(type: string) {
      this.$emit('action-click', type, null);
    },
    handleBtnClick({ name }, record) {
      this.$emit('action-click', name, record);
    },
  },
});
